package com.shebei.api.equipment_api_test.http;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientPutParam implements HttpClienInterface{




    @Override
    public String sendRequest(String url, String requestBody, Map<String, String> head) {
        if(requestBody==null){
            return doPutParam( url,  null, head);
        }
        Map param = JSONObject.parseObject(requestBody);
      String res=  doPutParam( url,  param, head);

        return res;
    }


    private   String doPutParam(String url, Map<String, String> param,Map<String, String> heard )  {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";


        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, String.valueOf(param.get(key)));
                }
            }
            URI uri = builder.build();
            System.out.println("请求URL为："+uri);
            // 创建http GET请求
            HttpPut httpPut = new HttpPut(uri);

            if (heard != null){
                for (String key : heard.keySet()) {
                    httpPut.setHeader(key,String.valueOf(heard.get(key)));
                }


            }



            // 执行http请求
            response = httpClient.execute(httpPut);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {

                e.printStackTrace();

        } finally {
            try {
                if (null!=response){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
